<template>
    <div class="location-selector">
      <select v-model="selectedCode" @change="onChange">
        <option value="">-- 选择存放位置 --</option>
        <optgroup v-for="(locs, type) in groupedLocations" :label="type">
          <option 
            v-for="loc in locs" 
            :key="loc.code"
            :value="loc.code"
            :disabled="loc.current_count >= loc.capacity"
          >
            {{ loc.code }}({{ loc.description }})
          </option>
        </optgroup>
      </select>
    </div>
  </template>
  
  <script>
  export default {
    props: ['modelValue'],
    data() {
      return {
        selectedCode: "",
        locations: []
      }
    },
    computed: {
      groupedLocations() {
        return this.locations.reduce((groups, loc) => {
          (groups[loc.type] = groups[loc.type] || []).push(loc)
          return groups
        }, {})
      }
    },
    methods: {
      async loadLocations() {
        try {
          const res = await this.$api.get('/locations')
          this.locations = res.data
        } catch (error) {
          console.error('Failed to load locations:', error)
        }
      },
      onChange(event) {
        this.$emit('update:modelValue', event.target.value)
      }
    },
    mounted() {
      this.loadLocations()
    }
  }
  </script>